package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.api.feign.aparticle.ApArticleFeignClient;
import com.heima.audit.tess4j.Tess4jClient;
import com.heima.common.constants.DelayConstants;
import com.heima.common.contentsecurity.ContentSecurityCheck;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author mr.luo
 * @Date 23 6月 2025 00:16
 */
@Slf4j
@Service
public class WmNewAutoScanServiceImpl implements WmNewAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private ApArticleFeignClient apArticleFeignClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private ContentSecurityCheck contentSecurityCheck;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ObjectMapper objectMapper; // JSON序列化工具
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private Tess4jClient tess4jClient;


    /**
     * 自动审核媒体文章
     *
     * @param id
     */

    @Async("articleReviewExecutor") // 指定使用上面配置的线程池
    @Override
    public void autoScanMediaNews(Integer id) {
        try {
            checkMediaNews(id); // 直接执行审核逻辑，由 @Async 异步执行
        } catch (Exception e) {
            log.error("文章审核任务执行异常，文章ID:{}", id, e);
            e.printStackTrace();
        }
    }

    private void checkMediaNews(Integer id) {
        log.info("开始审核文章:{}", id);
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("自媒体文章不存在");
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //2.调用百度进行审核
            //先拿到文章内容和图片
            String content = wmNews.getContent();
            String images = wmNews.getImages();
            List<String> list = Arrays.asList(images.split(","));

            //拿到标题
            String title = wmNews.getTitle();
            //拿到文本中的内容
            String s = extractText(content);
            String s1 = title + " " + s;
            //拿到文本中的图片
            Set<String> list1 = extractImage(content);
            list1.addAll(list);
            //检测文本内容自行检测
            String[] split = s1.split(" ");
            List<String> contantTexts = Arrays.asList(split);
            boolean b2 = handleSensitiveWords(contantTexts, wmNews);
            if (b2 == false) {
                wmNews.setStatus((short) 2);
                wmNews.setReason("审核不通过");
                log.error("文本内容违规");
            }
            //检测文本内容
            try {
                if (wmNews.getStatus() != 2) {
                    //使用百度云的接口进行，文本内容审核
                    boolean b = contentSecurityCheck.detectText(s1);
                    if (!b) {
                        wmNews.setStatus((short) 2);
                        wmNews.setReason("审核不通过");
                        log.error("文本内容违规");
                    }
                }
                log.info("文本内容审核结束,{}", wmNews.getStatus() == 2?"文本内容审核不通过":"审核通过");
                if (wmNews.getStatus() != 2) {
                    try {
                        for (String image : list1) {
                            log.info("开始审核图片:{}", image);
                            byte[] bytes = fileStorageService.downLoadFile(image);
                            //图片识别文字审核---begin-----
                            //从byte[]转换为butteredImage
                            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                            log.info("开始识别图片:{}", in);
                            BufferedImage imageFile = ImageIO.read(in);
                            //识别图片的文字
                            String result = tess4jClient.doOCR(imageFile);
                            //审核是否包含自管理的敏感词
                            boolean isSensitive = handleSensitiveWords(Collections.singletonList(result), wmNews);
                            if (isSensitive == false) {
                                wmNews.setStatus((short) 2);
                                wmNews.setReason("审核不通过");
                                log.error("图片内容文字违规");
                                break;
                            } else {
                                boolean b1 = true;
                                //检测图片内容
                                for (String s2 : list1) {
                                    b1 = contentSecurityCheck.inspectTheImage(s2);
                                    if (!b1) {
                                        wmNews.setStatus((short) 2);
                                        wmNews.setReason("审核不通过");
                                        log.error("图片内容违规");
                                        break;
                                    }
                                }

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (wmNews.getStatus() != 2) {
                    log.info("审核通过");
                    //4.审核成功保存app端的相关文章数据
                    ArticleDto dto = new ArticleDto();
                    BeanUtils.copyProperties(wmNews, dto);
                    //布局
                    dto.setLayout(wmNews.getType());
                    //频道
                    dto.setChannelId(wmNews.getChannelId());
                    //频道名称
                    WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
                    if (wmChannel != null) {
                        dto.setChannelName(wmChannel.getName());
                    }
                    //作者
                    dto.setAuthorId(Long.valueOf(wmNews.getUserId()));
                    //作者名称
                    WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
                    if (wmUser != null) {
                        dto.setAuthorName(wmUser.getName());
                    }
                    //设置文章id
                    if (wmNews.getArticleId() != null) {
                        dto.setId(wmNews.getArticleId());
                    }
                    dto.setCreatedTime(new Date());
                    //都合规
                    //- 审核通过，如果发布时间已到，远程调用app端新增article表的Feign接口;修改wmNews表的状态为9
                    //- 审核通过，如果发布时间未到，修改wmNews表的状态为8
                    //判断发布时间
                    ResponseResult responseResult = null;
                    if (wmNews.getPublishTime().getTime() < System.currentTimeMillis()) {
                        // 发布时间已到
                        log.info("发布时间已到,且审核通过");
                        wmNews.setStatus((short) 9);
                        wmNews.setReason("审核通过");
                        responseResult = apArticleFeignClient.save(dto);

                        if (null != responseResult && responseResult.getCode().equals(200)) {
                            //保存成功
                            log.info("apArticleFeignClient,保存成功");
                            System.out.println("apArticleFeignClient,保存成功");
                            wmNews.setArticleId((Long) responseResult.getData());
                        } else {
                            //保存失败
                            throw new RuntimeException("保存app端文章失败");
                        }
                    } else {
                        // 待发布
                        log.info("发布时间未到,且审核通过");
                        wmNews.setStatus((short) 8);
                        wmNews.setReason("审核通过");
                        log.info("发送到延迟队列，等待时间到之后进行发布");
                        //计算出发布时间与当前时间之间的差值
                        // 毫秒
                        long time = wmNews.getPublishTime().getTime() - System.currentTimeMillis();
                        //使用MQ发送延迟消息
                        // 1. 将对象转为JSON字符串
                        String jsonMessage = objectMapper.writeValueAsString(dto);
                        Message message = MessageBuilder.withBody(jsonMessage.getBytes(StandardCharsets.UTF_8))
                                .setHeader("x-delay", time)
                                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                .build();
                        //发送延迟消息
                        log.info("发送延迟消息:{}", message);
                        rabbitTemplate.convertAndSend(DelayConstants.DELAY_EXCHANGE_NAME,
                                DelayConstants.DELAY_WNMATERIAL_KEY, message);
                    }
                }
                wmNewsMapper.updateById(wmNews);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 提取文本
     */
    private String extractText(String content) {
        StringBuilder stringBuilder = new StringBuilder();
        //提取文章内容
        List<Map> maps = JSON.parseArray(content, Map.class);
        //提取文章图片
        for (Map map : maps) {
            if (map.get("type").equals("text")) {
                stringBuilder.append(map.get("value")).append(" ");
            }
        }
        return stringBuilder.toString();
    }


    /**
     * 提取图片
     */
    private Set<String> extractImage(String content) {
        Set<String> images = new HashSet<>();
        //提取文章内容
        List<Map> maps = JSON.parseArray(content, Map.class);
        //提取文章图片
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                images.add(map.get("value") + "");
            }
        }
        return images;
    }


    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    private boolean handleSensitiveWords(List<String> contentTexts, WmNews wmNews) {
        boolean isSensitive = true;
        //1.获取所有敏感词
        List<WmSensitive> wmSensitiveList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> collect = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //2.初始化敏感词库
        SensitiveWordUtil.initMap(collect);
        //3.遍历文章内容查看是否包含敏感词
        for (String contentText : contentTexts) {
            Map<String, Integer> map = SensitiveWordUtil.matchWords(contentText);
            if (map.size() > 0) {
                //4.如果包含敏感词，修改文章状态
//                wmNews.setStatus((short) 2);
//                wmNews.setReason("内容包含敏感词");
//                wmNewsMapper.updateById(wmNews);
                isSensitive = false;
                break;
            }
        }
        return isSensitive;
    }

}
